<?php

namespace Viettrans\FrontBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Viettrans\FrontBundle\Entity\Alert;
use Viettrans\FrontBundle\Form\AlertType;

/**
 * Alert controller.
 *
 * @Route("/alert")
 */
class AlertController extends Controller
{
	/**
     * Lists all Alert entities.
     *
     * @Route("/", name="alert")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entities = $em->getRepository('ViettransFrontBundle:Alert')->findAll();

        return array('entities' => $entities);
    }

    /**
     * Finds and displays a Alert entity.
     *
     * @Route("/{id}/show", name="alert_show")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('ViettransFrontBundle:Alert')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Alert entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        );
    }

    /**
     * Creates a new Alert entity.
     *
     * @Route("/create", name="alert_create")
     */
    public function createAction() {
		# Get Request
		$request = $this->getRequest();
		if(!$request->isXmlHttpRequest() && $this->getEnv() == 'prod') return new Response('', '403');

		# Get the variables
		$message = trim($request->get('message'));
		$announcementId = $request->get('announcementId');
		
		# If message is empty then return KO
		$messageLength = strlen($message);
		$maxAlertLength = $this->container->getParameter('max_alert_length');
		$minAlertLength = $this->container->getParameter('min_alert_length');
		if ($messageLength < $minAlertLength || $messageLength > $maxAlertLength) return new Response('{"code":"KO", "description":"Nội dung cảnh báo tối thiểu là '.$minAlertLength.' và tối đa là '.$maxAlertLength.' kí tự."}');
		
		# Get array of created alerts
		$createdAlerts = isset($_COOKIE['createdAlerts']) ? $_COOKIE['createdAlerts'] : '';
		$createdAlerts = explode("|", $createdAlerts);
		
		# If created yet then return KO
		if (in_array($announcementId, $createdAlerts)) return new Response('{"code":"KO", "description":"Bạn đã cảnh báo về tin đăng này rồi."}');
		
		# Get entity manager
		$em = $this->getDoctrine()->getEntityManager();		
		$announcement = $em->getRepository('ViettransFrontBundle:Announcement')->find($announcementId);
		if (!$announcement) return new Response('{"code":"KO", "description":"Tin đăng không tồn tại."}');
	
		# Get the userId
		$session = $this->get('session');
		$userId = $session->get('userId');
		
		# Create the alert object
		$alert = new Alert();
		if (isset($userId)) $alert->setUserId($userId);
		$alert->setAnnouncementId($announcementId);
		$alert->setMessage($message);
		
		# Persist
		try {
			$em->persist($alert);
			$em->flush();
			
			$alertCreated[] = $announcementId;
			$alertCreated = implode('|', $alertCreated);
			setcookie('createdAlerts', $alertCreated);
			
			return new Response('{"code":"OK", "description":"Viettrans xin chân thành cám ơn bạn."}');
			
		} catch(\Exception $e){
			return new Response('{"code":"KO", "description":"Lỗi hệ thống. Vui lòng liên hệ với Admin."}');
		}
    }

    /**
     * Displays a form to edit an existing Alert entity.
     *
     * @Route("/{id}/edit", name="alert_edit")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('ViettransFrontBundle:Alert')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Alert entity.');
        }

        $editForm = $this->createForm(new AlertType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Alert entity.
     *
     * @Route("/{id}/update", name="alert_update")
     * @Method("post")
     * @Template("ViettransFrontBundle:Alert:edit.html.twig")
     */
    public function updateAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('ViettransFrontBundle:Alert')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Alert entity.');
        }

        $editForm   = $this->createForm(new AlertType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('alert_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Alert entity.
     *
     * @Route("/{id}/delete", name="alert_delete")
     * @Method("post")
     */
    public function deleteAction($id)
    {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('ViettransFrontBundle:Alert')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Alert entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('alert'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
	
	private function getEnv() {
		return ($this->container->getParameter('kernel.environment') == 'prod') ? 'prod' : 'dev';
	}
}
